package com.lanyou.esb.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Tuple;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import redis.clients.jedis.exceptions.JedisException;

import com.lanyou.cook.datadictionary.UserLogOpt;
import com.lanyou.cook.entity.domain.FieldSystem;
import com.lanyou.cook.entity.domain.userManagement.User;
import com.lanyou.cook.repository.FieldSystemRepository;
import com.lanyou.cook.service.UserLogService;
import com.lanyou.esb.common.CommonUtils;
import com.lanyou.esb.datadictionary.AuditStatusType;
import com.lanyou.esb.datadictionary.EnableType;
import com.lanyou.esb.datadictionary.InterfaceIsPublicType;
import com.lanyou.esb.entity.Http;
import com.lanyou.esb.entity.Token;
import com.lanyou.esb.exception.ServiceAccessApplicationException;
import com.lanyou.esb.redis.proxy.impl.TokenJedisProxy;
import com.lanyou.esb.redis.vo.IfTokenVo;
import com.lanyou.esb.repository.TokenRepository;
import com.lanyou.esb.vo.TokenVo;

/**
 * 接口令牌服务
 * 
 * @author Davey.wu
 */
@Service
public class TokenService {
	@Autowired
	private TokenRepository tokenRepository;

	@Autowired
	private FieldSystemRepository fieldSystemRepository;

	@PersistenceContext
	private EntityManager entityManager;

	@Autowired
	private TokenJedisProxy tokenJedisProxy;

	@Autowired
	private UserLogService userLogService;

	/**
	 * 删除令牌<br>
	 * 描述：<br>
	 * 不作物理删除，只是把IS_ENABLE状态改为不可用
	 * 
	 * @param ids
	 * @throws ServiceAccessApplicationException
	 */
	@Transactional
	public void deleteToken(List<String> ids)
			throws ServiceAccessApplicationException {
		List<Token> list = tokenRepository.findAll(ids);
		if (list == null) {
			throw new ServiceAccessApplicationException("找不到相关的密钥信息", 2);
		}
		for (Token token : list) {
			token.setIsEnable(EnableType.DISABLE.ValueCode);
		}
		tokenRepository.save(list);
		delTokenRedisData(list);
		// 记录用户日志
		userLogService.save(UserLogOpt.MaintenanceServiceAccessApplication,
				null, String.format("删除令牌"));
	}

	/**
	 * 根据接口标识和用户编码获取令牌信息
	 * 
	 * @param ifId
	 *            ：接口标识
	 * @param userCode
	 *            ：用户编码
	 * @return
	 */
	public List<TokenVo> findToken(String ifId, String userCode) {

		// 获取结果集
		List<Object[]> objects = tokenRepository.findTokenByIfIdAndUserCode(
				ifId, userCode);
		// 无记录，返回空集
		if (objects == null || objects.isEmpty()) {
			return new ArrayList<>(0);
		}

		List<TokenVo> result = new ArrayList<>();
		// 转换结果
		for (Object[] object : objects) {
			TokenVo vo = new TokenVo();
			vo.setId((String) object[0]);
			vo.setAppKey((String) object[1]);
			vo.setIfId((String) object[2]);
			vo.setCallSytemCode((String) object[3]);
			vo.setCallSystemName((String) object[4]);
			result.add(vo);
		}
		return result;
	}

	// 删除Redis对应的数据
	private boolean delTokenRedisData(List<Token> tokens)
			throws ServiceAccessApplicationException {
		/* TokenJedisProxy tokenJedisProxy = new TokenJedisProxy(); */
		try {
			for (Token token : tokens) {
				IfTokenVo target = IfTokenVo.getInstance(token);
				tokenJedisProxy.hdel(target);
			}
		} catch (JedisException e) {
			throw new ServiceAccessApplicationException(
					CommonUtils.MSG_CONNECT_REDIS_FAIED,
					CommonUtils.CODE_CONNECT_REDIS_FAIED);
		} catch (Exception e) {
			throw new ServiceAccessApplicationException(
					CommonUtils.MSG_UPDATE_REDIS_DATA_FAIED,
					CommonUtils.CODE_UPDATE_REDIS_DATA_FAIED);
		}
		return true;
	}

}
